package com.bankcomm.ui.views;

import java.util.ArrayList;
import java.util.Map;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bankcomm.R;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BOCMainHome;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.util.LPUtils;
import com.rytong.tools.utils.AsyncImageLoader;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

/**
 * LPTopView.java
 * 
 * @author cheng.l 2013-5-18 下午01:17:55
 */
public class LPTopView extends LinearLayout {
	/**
	 * 图片下载 类
	 */
	private AsyncImageLoader loader ;
	
	private BaseViewCopy bv;
	private static LPWeatherView mWeatherView;
	private MyGallery mGallery;
	public GalleryAdapter adapter;
	private LinearLayout controller;
	
	private ArrayList<ImageView> imageViews = null;
	private int lastIndex = 0;
	ArrayList<Map<String, Object>> mList = new ArrayList<Map<String,Object>>() ;
	public LPTopView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		bv = (BaseViewCopy)context;
		init();
	}

	public LPTopView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		bv = (BaseViewCopy)context;
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		loader = Utils.getAsyncImageLoader();
		if(null == imageViews){
			imageViews = new ArrayList<ImageView>();
		}
		
		mWeatherView = new LPWeatherView(bv);
		mWeatherView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
		RelativeLayout view = (RelativeLayout) LayoutInflater.from(bv).inflate(R.layout.layout_top_view, null);

		controller = new LinearLayout(bv);
		controller.setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT);
		//controller.setBackgroundColor(R.color.toast_color);
		controller.setBackgroundColor(Color.TRANSPARENT);

		mGallery = new MyGallery(bv);
		adapter = new GalleryAdapter();
		mGallery.setAdapter(adapter);
		refresh();
		mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				Map<String, Object> weatherMap =  LPMid.getInstance().um_.data.adList.get(position);
				String contentURL = (String) weatherMap.get("contentURL");
				
				if (contentURL.equalsIgnoreCase("weather")) {
					// 弹出首页城市选择
					mWeatherView.onClick(null);
					return;
				}
				
				if(!LPToastUtil.isBuildChannel){
					((BOCMainHome)bv).showAlertDialog(true,null);
					return;
				}
				if(null != contentURL && !"".equalsIgnoreCase(contentURL) && !contentURL.equalsIgnoreCase("weather")){
					LPMid.getInstance().um_.doActionWithLink(bv,contentURL);
				}
			}
		});
		
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int index, long arg3) {
				setPoint(index);
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		RelativeLayout.LayoutParams lpg = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		lpg.addRule(RelativeLayout.CENTER_IN_PARENT);
		RelativeLayout.LayoutParams lpc = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,28);
		lpc.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		
		view.addView(mGallery,lpg);
		view.addView(controller,lpc);
		
		int height = LPUtils.screenheight/3-Utils.getScaledValueY(LPUtils.TITLE_HEIGHT);
		this.addView(view,new LayoutParams(LayoutParams.FILL_PARENT,height));
	}

	/**
	 * 得到view的高度
	 * @return
	 */
	public int getTopViewHeight(){
		return LPUtils.screenheight/3-Utils.getScaledValueY(LPUtils.TITLE_HEIGHT);
	}
	
	public void setPoint(int index){
		if(null != controller && controller.getChildCount() > 0){
			controller.getChildAt(lastIndex).setEnabled(true);
			controller.getChildAt(index).setEnabled(false);
			lastIndex = index;			
		}
	}

	public void refresh(){
		if(null != LPMid.getInstance().um_.data){
			mList = LPMid.getInstance().um_.data.adList;
		}
		controller.removeAllViews();
		int size = mList.size();
		imageViews.clear();
		for(int i = 0 ;i < size;i++){
			ImageView iv = new ImageView(bv);
			iv.setImageResource(R.drawable.gallery_point_selector);
			iv.setPadding(3, 3, 3, 3);
			iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
			controller.addView(iv);
		
			if(i != size-1){
				ImageView iv1 = new ImageView(bv);
				iv1.setScaleType(ScaleType.FIT_XY);
				iv1.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				imageViews.add(iv1);
			}
		}
		setPoint(0);
		adapter.notifyDataSetChanged();
	}
	
	/**
	 * 更新天气
	 */
	public void updateWeather(){
		mWeatherView.refresh();
	}
	
	/**
	 * 重写Gallery中的onFling方法是为了使得Gallery切换内容时一次只切换一屏
	 */
	public class MyGallery extends Gallery {

		public MyGallery(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
			this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
			this.setGravity(Gravity.CENTER);
			this.setSpacing(0);
			// 去掉边缘阴影
			this.setFadingEdgeLength(0);
		}

		public void showPageView(boolean left){
			if(left){
				this.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
			}else{
				this.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
			}
			
			this.invalidate();
		}
		
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			// TODO Auto-generated method stub
			int keyCode;
			/*
			 * 这样能够实现每次滑动只是滚动一张图片的效果 返回false也可以实现，但是需要滑动很大的距离图片才能切换，体验不好
			 */

			if (isScrollingLeft(e1, e2)) {
				keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
			} else {
				keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
			}
			onKeyDown(keyCode, null);

			return true;
		}

		public boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
			return e2.getX() > e1.getX();
		}
	}
	
	/**
	 * 跳转到WeatherView
	 * @param city
	 * @param xml
	 */
	public void gotoWeather(String city){
		if(mGallery.getSelectedItemPosition() != 0){
			mGallery.setSelection(0, true);			
		}
		mWeatherView.startRefresh(city);
	}
	
	public class GalleryAdapter extends BaseAdapter{
		public GalleryAdapter(){
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return LPMid.getInstance().um_.data.adList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int index, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			Map<String, Object> weatherMap =  mList.get(index);
			String imageURL = (String) weatherMap.get("imageURL");
			//返回日期控件
			if(null != imageURL && imageURL.equalsIgnoreCase("weather")){
				return mWeatherView;
			}
			
			//绑定图片
			loader.displayView(bv, imageViews.get(index-1), imageURL, R.drawable.img_ad_waiting,0);
			return imageViews.get(index-1);
		}
	}
	
	/**
	 * 释放资源 
	 */
	public void releaseResources(){
		if(null != imageViews){
			for(ImageView iv : imageViews){
				Utils.releaseObject(iv);
			}
			imageViews.clear();
			imageViews = null;
		}
		if(null != mWeatherView){
			mWeatherView.releaseResources();
			mWeatherView = null;
		}
	}
}
